<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GoldTree 前端调试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background: #f5f5f5;
        }
        .debug-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            max-width: 800px;
            margin: 0 auto;
        }
        .error-item {
            background: #ffebee;
            border-left: 4px solid #f44336;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .success-item {
            background: #e8f5e8;
            border-left: 4px solid #4caf50;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .warning-item {
            background: #fff3e0;
            border-left: 4px solid #ff9800;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .code-block {
            background: #263238;
            color: #ffffff;
            padding: 10px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            white-space: pre-wrap;
            margin: 10px 0;
        }
        button {
            background: #1890ff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background: #40a9ff;
        }
    </style>
</head>
<body>
    <div class="debug-container">
        <h1>🔧 GoldTree 前端调试工具</h1>
        <p>这个页面用于诊断前端JavaScript错误。</p>
        
        <div id="debug-results">
            <h3>📋 检查项目：</h3>
            <div id="checks"></div>
        </div>
        
        <h3>🛠️ 调试工具：</h3>
        <button onclick="runDiagnostics()">运行完整诊断</button>
        <button onclick="testAPI()">测试API连接</button>
        <button onclick="testLogin()">测试登录</button>
        <button onclick="checkConsoleErrors()">查看控制台错误</button>
        <button onclick="clearStorage()">清除存储</button>
        
        <div id="console-output">
            <h3>📄 控制台输出：</h3>
            <div class="code-block" id="console-log"></div>
        </div>
    </div>

    <script>
        let consoleMessages = [];
        
        // 拦截控制台输出
        const originalLog = console.log;
        const originalError = console.error;
        const originalWarn = console.warn;
        
        console.log = function(...args) {
            consoleMessages.push({ type: 'log', message: args.join(' '), time: new Date().toLocaleTimeString() });
            originalLog.apply(console, args);
            updateConsoleDisplay();
        };
        
        console.error = function(...args) {
            consoleMessages.push({ type: 'error', message: args.join(' '), time: new Date().toLocaleTimeString() });
            originalError.apply(console, args);
            updateConsoleDisplay();
        };
        
        console.warn = function(...args) {
            consoleMessages.push({ type: 'warn', message: args.join(' '), time: new Date().toLocaleTimeString() });
            originalWarn.apply(console, args);
            updateConsoleDisplay();
        };
        
        function updateConsoleDisplay() {
            const output = document.getElementById('console-log');
            const latest = consoleMessages.slice(-20); // 显示最新20条
            output.innerHTML = latest.map(msg => 
                `[${msg.time}] ${msg.type.toUpperCase()}: ${msg.message}`
            ).join('\n');
        }
        
        function addCheck(title, status, message) {
            const checks = document.getElementById('checks');
            const className = status === 'success' ? 'success-item' : (status === 'error' ? 'error-item' : 'warning-item');
            checks.innerHTML += `<div class="${className}"><strong>${title}:</strong> ${message}</div>`;
        }
        
        function runDiagnostics() {
            document.getElementById('checks').innerHTML = '';
            
            // 检查基础环境
            addCheck('浏览器兼容性', 'success', `用户代理: ${navigator.userAgent}`);
            
            // 检查JavaScript支持
            try {
                const testObj = { a: 1, b: 2 };
                const spread = { ...testObj };
                addCheck('ES6扩展运算符', 'success', '支持对象扩展运算符');
            } catch (e) {
                addCheck('ES6扩展运算符', 'error', `不支持: ${e.message}`);
            }
            
            // 检查可选链操作符
            try {
                const test = null;
                const result = test?.property;
                addCheck('可选链操作符', 'success', '支持可选链操作符 (?.)');
            } catch (e) {
                addCheck('可选链操作符', 'error', `不支持: ${e.message}`);
            }
            
            // 检查DOM元素
            const requiredElements = ['stocks-content', 'dashboard', 'modals'];
            requiredElements.forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    addCheck(`DOM元素#${id}`, 'success', '元素存在');
                } else {
                    addCheck(`DOM元素#${id}`, 'error', '元素不存在');
                }
            });
            
            // 检查必要函数
            const requiredFunctions = ['showAlert', 'showLoginModal', 'loadStocksList'];
            requiredFunctions.forEach(funcName => {
                if (typeof window[funcName] === 'function') {
                    addCheck(`函数${funcName}`, 'success', '函数已定义');
                } else {
                    addCheck(`函数${funcName}`, 'error', '函数未定义');
                }
            });
            
            // 检查localStorage
            try {
                localStorage.setItem('test', 'test');
                localStorage.removeItem('test');
                addCheck('localStorage', 'success', 'localStorage可用');
            } catch (e) {
                addCheck('localStorage', 'error', `localStorage不可用: ${e.message}`);
            }
            
            // 检查fetch API
            if (typeof fetch === 'function') {
                addCheck('Fetch API', 'success', 'Fetch API可用');
            } else {
                addCheck('Fetch API', 'error', 'Fetch API不可用');
            }
        }
        
        async function testAPI() {
            try {
                addCheck('API测试', 'warning', '正在测试API连接...');
                const response = await fetch('http://localhost:8080/api/health');
                if (response.ok) {
                    addCheck('API连接', 'success', 'API服务器连接正常');
                } else {
                    addCheck('API连接', 'error', `API响应错误: ${response.status}`);
                }
            } catch (e) {
                addCheck('API连接', 'error', `API连接失败: ${e.message}`);
            }
        }
        
        function testLogin() {
            const token = localStorage.getItem('goldtree_token');
            if (token) {
                addCheck('登录状态', 'success', `已登录，token: ${token.substring(0, 20)}...`);
            } else {
                addCheck('登录状态', 'warning', '未登录或token已过期');
            }
        }
        
        function checkConsoleErrors() {
            const errors = consoleMessages.filter(msg => msg.type === 'error');
            if (errors.length === 0) {
                addCheck('控制台错误', 'success', '没有发现JavaScript错误');
            } else {
                errors.forEach(error => {
                    addCheck('JavaScript错误', 'error', `${error.time}: ${error.message}`);
                });
            }
        }
        
        function clearStorage() {
            localStorage.clear();
            sessionStorage.clear();
            addCheck('清除存储', 'success', '已清除所有本地存储数据');
        }
        
        // 页面加载时自动运行诊断
        window.addEventListener('load', function() {
            console.log('调试页面已加载，开始运行诊断...');
            setTimeout(runDiagnostics, 500);
        });
        
        // 捕获全局错误
        window.addEventListener('error', function(event) {
            addCheck('全局JavaScript错误', 'error', `${event.filename}:${event.lineno} - ${event.message}`);
        });
        
        window.addEventListener('unhandledrejection', function(event) {
            addCheck('未处理Promise拒绝', 'error', event.reason.toString());
        });
    </script>
</body>
</html>